package com.kotlin.myapplicationd.tools;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Camera;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;


import com.kotlin.library.utils.SPUtils;
import com.kotlin.myapplicationd.MApplication;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * 运行环境信息
 *
 * @author xudong
 * @version 1.0
 */
public final class SysEnv {

    /**
     * 手机型号(GT-I9100G)
     ***/
    public static final String MODEL_NUMBER = Build.MODEL;
    /**
     * 手机品牌(GT-I9100G)
     ***/
    public static final String BRAND = Build.BRAND;
    /**
     * 操作系统名称(I9100G)
     ***/
    public static final String DISPLAY_NAME = Build.DISPLAY;
    /**
     * 操作系统版本(4.4)
     ***/
    public static final String OS_VERSION = Build.VERSION.RELEASE;
    /***
     * Activity之间数据传输数据对象Key
     **/
    public static final String ACTIVITY_DTO_KEY = "ACTIVITY_DTO_KEY";
    /***
     * Log输出标识
     **/
    private static final String TAG = SysEnv.class.getSimpleName();
    /***
     * 屏幕显示材质
     **/
    private static final DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    /**
     * 上下文
     **/
    private static final Context context = MApplication.gainContext();
    /**
     * 应用程序版本
     ***/
    public static final String APP_VERSION = getVersionName();
    /***
     * 屏幕宽度
     **/
    public static final int SCREEN_WIDTH = getDisplayMetrics().widthPixels;
    /***
     * 屏幕高度
     **/
    public static final int SCREEN_HEIGHT = getDisplayMetrics().heightPixels;

    /***
     * 本机手机号码
     **/
//	public static final String PHONE_NUMBER = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
//
//	/***设备ID**/
//	//TODO 加入权限检查
//	public static final String DEVICE_ID = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
//
//	/***设备IMEI号码**/
//	public static final String IMEI = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
//
//	/***设备IMSI号码**/
//	public static final String IMSI = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
    public static String getPhoneNumber() {
        return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
    }

    public static String getDeviceId() {
        return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    }

    public static String getIMEI() {
        //MApplication.getDiskLruHelper().put(ThirdLoginBean.ThirdLoginSerializableTag,(Serializable) loginBean);
        String IMEI = "";

        if (!TextUtils.isEmpty(SPUtils.getString(context, "IMEI")))
            return SPUtils.getString(context, "IMEI");

        if (RxPermissions.getInstance(context).isGranted(Manifest.permission.READ_PHONE_STATE)) {
            IMEI = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
            SPUtils.putString(context, "IMEI", IMEI);
        } else {
            //ToolAlert.toast(context.getString(R.string.request_phone_permission), Toast.LENGTH_SHORT);
            IMEI = SPUtils.getString(context, "IMEI");
        }
        return IMEI;
    }

    public static String getIMSI() {
        //return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();

        String IMSI = "";

        if (!TextUtils.isEmpty(SPUtils.getString(context, "IMSI")))
            return SPUtils.getString(context, "IMSI");

        if (RxPermissions.getInstance(context).isGranted(Manifest.permission.READ_PHONE_STATE)) {
            IMSI = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
            SPUtils.putString(context, "IMSI", IMSI);
        } else {
            //ToolAlert.toast(context.getString(R.string.request_phone_permission), Toast.LENGTH_SHORT);
            IMSI = SPUtils.getString(context, "IMSI");
        }
        return IMSI;

    }

    /**
     * 获取系统显示材质
     ***/
    public static DisplayMetrics getDisplayMetrics() {
        WindowManager windowMgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowMgr.getDefaultDisplay().getMetrics(mDisplayMetrics);
        return mDisplayMetrics;
    }

    /**
     * 获取摄像头支持的分辨率
     ***/
    public static List<Camera.Size> getSupportedPreviewSizes(Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();
        return sizeList;
    }

    /**
     * 获取应用程序版本（versionName）
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName() {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            Log.e(TAG, "获取应用程序版本失败，原因：" + e.getMessage());
            return "";
        }

        return info.versionName;
    }

    /**
     * 获取应用程序版本（versionName）
     *
     * @return 当前应用的版本号
     */
    public static int getVersionCode() {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            Log.e(TAG, "获取应用程序版本失败，原因：" + e.getMessage());
            return -1;
        }

        return info.versionCode;
    }

    /**
     * 获取系统内核版本
     *
     * @return
     */
    public static String getKernelVersion() {
        String strVersion = "";
        FileReader mFileReader = null;
        BufferedReader mBufferedReader = null;
        try {
            mFileReader = new FileReader("/proc/version");
            mBufferedReader = new BufferedReader(mFileReader, 8192);
            String str2 = mBufferedReader.readLine();
            strVersion = str2.split("\\s+")[2];//KernelVersion

        } catch (Exception e) {
            Log.e(TAG, "获取系统内核版本失败，原因：" + e.getMessage());
        } finally {
            try {
                mBufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return strVersion;
    }


    /***
     * 获取MAC地址
     *
     * @return
     */
    public static String getMacAddress() {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getMacAddress() != null) {
            return wifiInfo.getMacAddress();
        } else {
            return "";
        }
    }

    /**
     * 获取运行时间
     *
     * @return 运行时间(单位/s)
     */
    public static long getRunTimes() {
        long ut = SystemClock.elapsedRealtime() / 1000;
        if (ut == 0) {
            ut = 1;
        }
        return ut;
    }

    /**
     * 判断是否为模拟器环境需要权限
     * <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     *
     * @param mContext 上下文
     * @return
     */
    public static boolean isEmulator(Context mContext) {
        TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceID = telephonyManager.getDeviceId();
        // 如果 运行的 是一个 模拟器
        if (deviceID == null || deviceID.trim().length() == 0
                || deviceID.matches("0+")) {
            return true;
        }
        return false;
    }


    /***
     * 获取基站信息
     *
     * @return
     */
    public static String getBaseStation() {

        if (!RxPermissions.getInstance(context).isGranted(
                Manifest.permission.READ_PHONE_STATE) || !RxPermissions.getInstance(context).isGranted(
                Manifest.permission.ACCESS_COARSE_LOCATION)) {
            //IMSI = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();

            return SPUtils.getString(context, "BaseStation", "");
        }

        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        List<NeighboringCellInfo> infos = telephonyManager.getNeighboringCellInfo();
        //List<CellInfo> infos = telephonyManager.getAllCellInfo();
        if (infos != null) {
            StringBuffer sb = new StringBuffer("总数 : " + infos.size() + "\n");
            for (NeighboringCellInfo info1 : infos) { // 根据邻区总数进行循环
                sb.append(" LAC : " + info1.getLac()); // 取出当前邻区的LAC
                sb.append(" CID : " + info1.getCid()); // 取出当前邻区的CID
                sb.append(" BSSS : " + (-113 + 2 * info1.getRssi()) + "\n"); // 获取邻区基站信号强度
            }

            SPUtils.putString(context, "BaseStation", sb.toString());
            return sb.toString();

        } else {
            return "";
        }
    }

}
